"""
Case Type   : 共享存储-系统内部工具-dsscmd
Case Name   : dsscmd工具显示磁盘信息，指定block_id
Create At   : 2024/2/6
Owner       : songjing20
Description :
    1.显示磁盘信息，指定-g vg_name,-b block_id和-n node_id参数为有效值
    2.显示磁盘信息，指定-g vg_name参数为无效值
    3.显示磁盘信息，指定-b block_id参数为无效值
    4.在dss关闭的情况下执行显示磁盘信息
    5.在集群停止的情况下执行
    6.DSS_HOME路径权限不足时，显示磁盘信息，不指定-D DSS_HOME参数
    7.在备机显示磁盘信息
    8.显示磁盘信息，指定-D DSS_HOME参数为正常值
    9.显示磁盘信息，指定指定错误的-D DSS_HOME参数和权限不足的socket_domain
Expect      :
    1.显示成功
    2.合理报错
    3.合理报错
    4.显示成功
    5.显示成功
    6.合理报错
    7.显示成功
    8.显示成功
    9.合理报错
History     :
"""
import os
import time
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == Primary_SH.get_node_num(), '单机环境不执行')
class ShareStorageTool(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.primary_node = Node('PrimaryDbUser')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.standby_node = Node('Standby1DbUser')
        self.common = Common()
        self.constant = Constant()
        self.logger.info("-----获取卷组名-----")
        cmd = f"source {macro.DB_ENV_PATH};dsscmd lsvg;"
        self.logger.info(cmd)
        cmd_res = self.common.get_sh_result(self.primary_node, cmd)
        self.assertIn("Succeed to display lsvg info", cmd_res, "获取卷组名失败")
        self.vg_name = cmd_res.splitlines()[1].split()[0].strip()
        self.debug_log_path = os.path.join(
            macro.DSS_INSTANCE, 'log', 'debug', 'dsscmd.dlog')

    def test_sharestorage_tool(self):
        text = "-----step1:显示磁盘信息，指定-g vg_name,-b block_id" \
               "和-n node_id参数为有效值;expect:显示成功-----"
        self.logger.info(text)
        cmd = f"source {macro.DB_ENV_PATH};dsscmd getcfg -n _LOG_LEVEL"
        self.logger.info(cmd)
        res = self.common.get_sh_result(self.primary_node, cmd)
        self.assertIn('Succeed to get cfg, name is _LOG_LEVEL',res,
                      f'获取log_level失败:{text}')
        default_log_level = res.split('value is ')[-1].strip('.')
        shell_cmd = f"source {macro.DB_ENV_PATH};" \
                    f"dsscmd setcfg -n _LOG_LEVEL -v 255;sleep 3;" \
                    f"grep blockid {self.debug_log_path} | tail -n 1"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.primary_node, shell_cmd)
        blockid = shell_msg.split('metaid:')[-1].split()[0]
        cmd = f"source {macro.DB_ENV_PATH};" \
              f"dsscmd setcfg -n _LOG_LEVEL -v {default_log_level};"
        self.logger.info(cmd)
        res = self.common.get_sh_result(self.primary_node, cmd)
        self.assertIn(f'Succeed to set cfg, name is _LOG_LEVEL, value is'
                      f' {default_log_level}', res, f'获取log_level失败:{text}')
        cmd = f"source {macro.DB_ENV_PATH};" \
              f"dsscmd showdisk -g {self.vg_name} -b {blockid} -n 0;" \
              f"dsscmd showdisk --vg_name {self.vg_name} " \
              f"--block_id {blockid} --node_id 0"
        self.logger.info(cmd)
        cmd_res = self.common.get_sh_result(self.primary_node, cmd)
        flag = f'Succeed to printf dss file block with block_id:{blockid}'
        self.assertEquals(2, cmd_res.count(flag), f"执行失败:{text}")

        text = "-----step2:显示磁盘信息，指定-g vg_name参数为无效值;expect:合理报错-----"
        self.logger.info(text)
        cmd = f"source {macro.DB_ENV_PATH};" \
              f"dsscmd showdisk -g {self.vg_name}_not_exists -b {blockid} -n 0;" \
              f"dsscmd showdisk -g {self.vg_name}卷组 -b {blockid} -n 0;" \
              f"dsscmd showdisk -g {self.vg_name}@#^% -b {blockid} -n 0"
        self.logger.info(cmd)
        cmd_res = self.common.get_sh_result(self.primary_node, cmd)
        self.assertIn(f'Failed to get vg {self.vg_name}_not_exists.',
                      cmd_res, f"执行失败:{text}")
        self.assertIn(f'Path {self.vg_name}卷组 decode error , name should be '
                      f'[0~9,a~z,A~Z,-,_,.]', cmd_res, f"执行失败:{text}")
        self.assertIn(f'Path {self.vg_name}@#^% decode error , name should be '
                      f'[0~9,a~z,A~Z,-,_,.]', cmd_res, f"执行失败:{text}")

        text = "-----step3:显示磁盘信息，指定-b block_id参数为无效值;expect:合理报错-----"
        self.logger.info(text)
        cmd = f'''source {macro.DB_ENV_PATH};
            dsscmd showdisk -g {self.vg_name} -b 0 -n 0;
            dsscmd showdisk -g {self.vg_name} -b {blockid}试试 -n 0;
            dsscmd showdisk -g {self.vg_name} -b {blockid}@#$ -n 0;
            dsscmd showdisk -g {self.vg_name} -b aaw -n 0'''
        self.logger.info(cmd)
        cmd_res = self.common.get_sh_result(self.primary_node, cmd)
        self.assertIn('Failed to printf dss file block with block_id:0.',
                      cmd_res, f"执行失败:{text}")
        self.assertEquals(3, cmd_res.count(
            "Value error: Convert uint64 failed, the text is not number"),
                          f"执行失败:{text}")

        text = "-----step4:在dss关闭的情况下执行显示磁盘信息;expect:显示成功-----"
        self.logger.info(text)
        cmd = f"source {macro.DB_ENV_PATH}; " \
              f"dsscmd stopdss; " \
              f"dsscmd showdisk -g {self.vg_name} -b {blockid} -n 0; " \
              f"dsscmd showdisk --vg_name {self.vg_name} --block_id " \
              f"{blockid} --node_id 0"
        self.logger.info(cmd)
        cmd_res = self.common.get_sh_result(self.primary_node, cmd)
        self.assertEquals(2, cmd_res.count(flag), f"执行失败:{text}")

        text = "-----step5:在dss关闭的情况下执行显示磁盘信息;expect:显示成功-----"
        self.logger.info(text)
        stop_msg = self.primary_sh.exec_cm_ctl(mode='stop')
        self.logger.info(stop_msg)
        self.assertIn(self.constant.cm_stop_success_msg,
                      stop_msg, '执行失败' + text)
        cmd = f"source {macro.DB_ENV_PATH};" \
              f"dsscmd showdisk -g {self.vg_name} -b {blockid} -n 0;" \
              f"dsscmd showdisk --vg_name {self.vg_name} --block_id " \
              f"{blockid} --node_id 0"
        self.logger.info(cmd)
        cmd_res = self.common.get_sh_result(self.primary_node, cmd)
        self.assertEquals(2, cmd_res.count(flag), f"执行失败:{text}")
        start_msg = self.primary_sh.exec_cm_ctl(mode='start')
        self.logger.info(start_msg)
        self.assertIn(self.constant.cm_start_success_msg,
                      start_msg, '启动集群失败')
        time.sleep(30)
        status = self.primary_sh.exec_cm_ctl(mode='query', param='-Cv')
        self.logger.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败')

        text = "-----step6:DSS_HOME路径权限不足时，显示磁盘信息，" \
               "不指定-D DSS_HOME参数;expect:合理报错-----"
        self.logger.info(text)
        cmd = f'''source {macro.DB_ENV_PATH};
        chmod 000 {macro.DSS_INSTANCE};
        dsscmd showdisk -g {self.vg_name} -b {blockid} -n 0;
        dsscmd showdisk --vg_name {self.vg_name} --block_id {blockid} \
        --node_id 0;
        chmod 700 {macro.DSS_INSTANCE}'''
        self.logger.info(cmd)
        cmd_res = self.common.get_sh_result(self.primary_node, cmd)
        self.assertEquals(2, cmd_res.count(
            "dss_inst.ini does not exist"), f"执行失败:{text}")

        text = "-----step7:在备机显示磁盘信息;expect:显示成功-----"
        self.logger.info(text)
        cmd = f"source {macro.DB_ENV_PATH};" \
              f"dsscmd showdisk -g {self.vg_name} -b {blockid} -n 0;" \
              f"dsscmd showdisk --vg_name {self.vg_name} " \
              f"--block_id {blockid} --node_id 0"
        self.logger.info(cmd)
        cmd_res = self.common.get_sh_result(self.standby_node, cmd)
        self.assertEquals(2, cmd_res.count(flag), f"执行失败:{text}")

        text = "-----step8:显示磁盘信息，指定-D DSS_HOME参数为正常值;expect:显示成功-----"
        self.logger.info(text)
        cmd = f"source {macro.DB_ENV_PATH};" \
              f"dsscmd showdisk -g {self.vg_name} -b {blockid} " \
              f"-n 0 -D {macro.DSS_INSTANCE};" \
              f"dsscmd showdisk --vg_name {self.vg_name} " \
              f"--block_id {blockid} --node_id 0 -D {macro.DSS_INSTANCE}"
        self.logger.info(cmd)
        cmd_res = self.common.get_sh_result(self.primary_node, cmd)
        self.assertEquals(2, cmd_res.count(flag), f"执行失败:{text}")

        text = "-----step9:显示磁盘信息，指定指定错误的-D DSS_HOME参数和" \
               "权限不足的socket_domain;expect:合理报错-----"
        self.logger.info(text)
        cmd = f"source {macro.DB_ENV_PATH};" \
              f"dsscmd showdisk -g {self.vg_name} -b {blockid} -n 0 " \
              f"-D {macro.DSS_INSTANCE}_error;" \
              f"dsscmd showdisk --vg_name {self.vg_name} --block_id {blockid} " \
              f"--node_id 0 -D {macro.DSS_INSTANCE}_error;" \
              f"chmod 000 {macro.DSS_INSTANCE};" \
              f"dsscmd showdisk -g {self.vg_name} -b {blockid} " \
              f"-n 0 -D {macro.DSS_INSTANCE};" \
              f"dsscmd showdisk --vg_name {self.vg_name} --block_id {blockid} " \
              f"--node_id 0 -D {macro.DSS_INSTANCE};" \
              f"chmod 700 {macro.DSS_INSTANCE};"
        self.logger.info(cmd)
        cmd_res = self.common.get_sh_result(self.primary_node, cmd)
        self.assertEquals(4, cmd_res.count("Failed to load config info!"),
                          f"执行失败:{text}")
        self.assertEquals(4, cmd_res.count("dss_inst.ini does not exist"),
                          f"执行失败:{text}")

    def tearDown(self):
        self.logger.info("-----无需清理环境-----")
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
